package main

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

// 插入数据
func insertRowDemo(db *sql.DB) {
	sqlStr := "insert into user(name,age) values(?,?)"
	ret, err := db.Exec(sqlStr, "alen", 18)
	if err != nil {
		fmt.Printf("insert failed, errs:%v\n", err)
		return
	}

	theId, err := ret.LastInsertId() // 插入新数据的id
	if err != nil {
		fmt.Printf("get LastInsert ID faild, errs:%v\n", err)
		return
	}
	fmt.Printf("insert success, the id is %d.\n", theId)

}

func main() {
	db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.12.9:3306)/go_project?charset=utf8mb4")
	fmt.Println("errs:", err)
	err = db.Ping()
	if err != nil {
		fmt.Println("数据库连接失败", err)
		return
	}

	insertRowDemo(db)
	defer db.Close()

}
